package com.myproject.thread;

public class DeadLock {

    private static Object obj1 = new Object();
    private static Object obj2 = new Object();
    private static volatile int var1 = 0;
    private static volatile int var2 = 0;

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                synchronized (obj1){
                    System.out.println(name+" get lock1, try to get lock2");
                    var1 = 1;
                    while (var2!=1){}
                    System.out.println(name+" var2 is "+var2+", try to get lock2");
                    synchronized (obj2){
                        System.out.println(name+" get lock2");
                    }
                }

                System.out.println(name+" over");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                synchronized (obj2){
                    System.out.println(name+" get lock2, try to get lock1");
                    var2 = 1;
                    while (var1!=1){}
                    System.out.println(name+" var1 is "+var1+", try to get lock1");
                    synchronized (obj1){
                        System.out.println(name+" get lock1");
                    }
                }
                System.out.println(name+" over");
            }
        });

        t1.start();
        t2.start();
    }

}
